package com.haochang.chunkvod.controller.fragment.hostess;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.config.ServerErrorCodeConfig;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;

/**
 *         created at 2016/8/25 16:27
 *         房间管理 - 使用中页面
 */
public class RoomUsingFragment extends BaseFragment implements KeyBoardDialog.KeyBoardOnSureListener
{
	private BaseTextView tv_room_num, room_grant;
	private BaseEditText room_coun_h, room_coun_m;
	private Button room_using_clear, room_using_to_none, room_using_add_time;
	//授权
	private LinearLayout group_room_grant;
	//授权是否成功小icon及右箭头隐藏
	private ImageView iv_granted_success, iv_arrow_right;
	private String roomNum = "";

	private HostessData hostessData;
	private String token;
	private String roomId;
	private String billId;
	private String roomTypeId;
	private String expectedTime;

	private BaseEditText current_et;
	//是否已通过权限验证
	private boolean hasAuthorized = false;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_room_using, container, false);
		hostessData = new HostessData((BaseActivity) getActivity());
		initView(view);
		return view;
	}

	private void initView(View view)
	{
		Button room_using_ok = (Button) view.findViewById(R.id.room_using_ok);//底部确认按钮
		BaseTextView room_last_time = (BaseTextView) view.findViewById(R.id.room_last_time);//预结时间
		Button btn_room_num = (Button) view.findViewById(R.id.btn_room_num);//重新生成按钮
		iv_granted_success = (ImageView) view.findViewById(R.id.iv_granted_success);
		iv_arrow_right = (ImageView) view.findViewById(R.id.iv_arrow_right);
		tv_room_num = (BaseTextView) view.findViewById(R.id.tv_room_num);
		room_coun_h = (BaseEditText) view.findViewById(R.id.room_coun_h);
		room_coun_m = (BaseEditText) view.findViewById(R.id.room_coun_m);
		room_grant = (BaseTextView) view.findViewById(R.id.room_grant);
		room_using_clear = (Button) view.findViewById(R.id.room_using_clear);
		room_using_to_none = (Button) view.findViewById(R.id.room_using_to_none);
		room_using_add_time = (Button) view.findViewById(R.id.room_using_add_time);
		group_room_grant = (LinearLayout) view.findViewById(R.id.group_room_grant);
		room_coun_h.setOnClickListener(etClick);
		room_coun_m.setOnClickListener(etClick);
		btn_room_num.setOnClickListener(onBaseClickListener);
		room_using_clear.setOnClickListener(onBaseClickListener);
		room_using_to_none.setOnClickListener(onBaseClickListener);
		room_using_add_time.setOnClickListener(onBaseClickListener);
		room_using_ok.setOnClickListener(onBaseClickListener);
		group_room_grant.setOnClickListener(onBaseClickListener);

		room_coun_h.addTextChangedListener(watcher);
		room_coun_m.addTextChangedListener(watcher);

		roomId = getArguments().getString(IntentKey.ROOM_ID);
		billId = getArguments().getString(IntentKey.BILL_ID);
		roomTypeId = getArguments().getString(IntentKey.ROOM_TYPE_ID);
		expectedTime = getArguments().getString(IntentKey.EXP_TIME);
		roomNum = getArguments().getString(IntentKey.RELATE_CODE);
		tv_room_num.setText(roomNum);

		String[] strs = TimeUtils.getMinutesString(expectedTime).split(":");
		if (strs.length == 2)
		{
			String time = strs[0] + "时" + strs[1] + "分";
			room_last_time.setText(time);
		}
		showLastTime();
	}

	private TextWatcher watcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			if (Integer.parseInt(room_coun_h.getText().toString().trim()) > 23)
			{
				room_coun_h.setText(String.valueOf("23"));
			}
			if (Integer.parseInt(room_coun_m.getText().toString().trim()) > 59)
			{
				room_coun_m.setText(String.valueOf("59"));
			}
		}

		@Override
		public void afterTextChanged(Editable s)
		{

		}
	};

	/**
	 * 显示最大预结时间
	 */
	private void showLastTime()
	{
		hostessData.requestMostStatementTime(roomTypeId, billId, new HostessData.StatementTimeListener()
		{
			@Override
			public void onRequestSuccess(String time, long serverTime)
			{
				if (!TextUtils.isEmpty(time))
				{
					expectedTime = time;
					String[] strs = TimeUtils.getMinutesString(time).split(":");
					if (strs.length == 2)
					{
						room_coun_h.setText(strs[0]);
						room_coun_m.setText(strs[1]);
					}
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				if (errno != ServerErrorCodeConfig.SERVER_ERR)
				{
					ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "获取最大预结时间失败!" : errMsg);
				}
			}
		});
	}

	private OnBaseClickListener etClick = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			current_et = (BaseEditText) v;
			KeyBoardDialog keyBoardDialog = new KeyBoardDialog(getActivity());
			keyBoardDialog.setKeyBoardOnSureListener(RoomUsingFragment.this);
			keyBoardDialog.show();
		}
	};

	private OnBaseClickListener onBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.group_room_grant:
				//权限验证
				Intent intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
				intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.HOSTESS_GRANT_OPEN);
				startActivityForResult(intent, IntentCode.HOSTESS_GRANT_REQUEST);
				break;
			case R.id.btn_room_num:
				//重新生成房间码
				resetRoomNum();
				break;
			case R.id.room_using_clear:
				//清洁房间
				clear();
				break;
			case R.id.room_using_to_none:
				toNone();
				//转为空房
				break;
			case R.id.room_using_add_time:
				//延长续时
				hostessData.requestMostStatementTimeManager(roomTypeId, billId, new HostessData.StatementTimeListener()
				{
					@Override
					public void onRequestSuccess(String time, long serverTime)
					{
						expectedTime = time;
						String[] strs = TimeUtils.getMinutesString(time).split(":");
						if (strs.length == 2)
						{
							room_coun_h.setText(strs[0]);
							room_coun_m.setText(strs[1]);
							ToastUtils.showText(getActivity(), "成功延时至" + strs[0] + ":" + strs[1]);
						}
					}

					@Override
					public void onFail(int errno, String errMsg)
					{
						if (errno != ServerErrorCodeConfig.SERVER_ERR)
						{
							ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "延长续时失败!" : errMsg);
						}
					}
				});

				break;
			case R.id.room_using_ok:
				//提交数据,刷新数据
				String time = expectedTime.substring(0, 11) + room_coun_h.getText().toString().trim() + ":" + room_coun_m.getText().toString().trim() + ":00";
				hostessData.requestUpdateExpTime(billId, roomTypeId, time, roomNum, token, new HostessData.NoticeListener()
				{
					@Override
					public void onRequestSuccess(String code)
					{
						if (!TextUtils.isEmpty(code))
						{
							ToastUtils.showText(getActivity(), "续时成功");
							getActivity().finish();
						}
					}

					@Override
					public void onFail(int errno, String errMsg)
					{
						if (errno != ServerErrorCodeConfig.SERVER_ERR)
						{
							ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "延长续时失败!" : errMsg);
						}
						if (errno == ServerErrorCodeConfig.AUTHORIZATION_ERROR)
						{//授权失败
							hasAuthorized = false;
							refreshAuthorizationView();
						}
					}
				});
				break;
			}

		}
	};

	/**
	 * 转为空房
	 */
	private void toNone()
	{
		new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
				.cancelable(true).contentName("该房间正在使用，确定要转为空房吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{

					}

					@Override
					public void onOkClick()
					{
						if (!TextUtils.isEmpty(token))
						{
							hostessData.setRoomToEmptyManager(roomId, token, new HostessData.NoticeListener()
							{
								@Override
								public void onRequestSuccess(String notice)
								{
									if (!TextUtils.isEmpty(notice))
									{
										getActivity().finish();
										ToastUtils.showText(getActivity(), "该房间已被转为空房!");
									}
								}

								@Override
								public void onFail(int errno, String errMsg)
								{
									if (errno != ServerErrorCodeConfig.SERVER_ERR)
									{
										ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "转为空房失败!" : errMsg);
									}
								}
							});
						} else
						{
							ToastUtils.showText(getActivity(), "请先获取权限");
						}
					}

					@Override
					public void onCancelClick()
					{

					}
				}).build().show();
	}

	/**
	 * 清洁房间
	 */
	private void clear()
	{
		new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
				.cancelable(true).contentName("该房间正在使用，确定要清洁吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{

					}

					@Override
					public void onOkClick()
					{
						if (!TextUtils.isEmpty(token))
						{
							hostessData.setRoomToClearManager(roomId, token, new HostessData.NoticeListener()
							{
								@Override
								public void onRequestSuccess(String notice)
								{
									if (!TextUtils.isEmpty(notice))
									{
										getActivity().finish();
										ToastUtils.showText(getActivity(), "该房间已被更改为清洁状态!");
									}
								}

								@Override
								public void onFail(int errno, String errMsg)
								{
									if (errno != ServerErrorCodeConfig.SERVER_ERR)
									{
										ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "更改房间状态失败!" : errMsg);
									}
								}
							});
						} else
						{
							ToastUtils.showText(getActivity(), "请先获取权限");
						}
					}

					@Override
					public void onCancelClick()
					{

					}
				}).build().show();
	}

	//重新获取房间码
	private void resetRoomNum()
	{
		new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
				.cancelable(true).contentName("确认要重新生成该房间的房间码？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{

					}

					@Override
					public void onOkClick()
					{
						//重新生成房间码
						if (!TextUtils.isEmpty(billId))
						{
							hostessData.requestRoomCode(billId, new HostessData.NoticeListener()
							{
								@Override
								public void onRequestSuccess(String code)
								{
									if (!TextUtils.isEmpty(code))
									{
										roomNum = code;
										tv_room_num.setText(roomNum);
										ToastUtils.showText(getActivity(), "已生成新的房间码");
									}
								}

								@Override
								public void onFail(int errno, String errMsg)
								{
									if (errno != ServerErrorCodeConfig.SERVER_ERR)
									{
										ToastUtils.showText(getActivity(), TextUtils.isEmpty(errMsg) ? "生成房间码失败!" : errMsg);
									}
								}
							});
						}
					}

					@Override
					public void onCancelClick()
					{

					}
				}).build().show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.HOSTESS_GRANT_REQUEST && resultCode == FragmentActivity.RESULT_OK && data != null)
		{
			token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			if (!TextUtils.isEmpty(token))
			{
				hasAuthorized = true;
				refreshAuthorizationView();
			}
		}
	}

	/**
	 * 根据权限是否验证通过显示下方的内容
	 */
	private void refreshAuthorizationView()
	{

		if (hasAuthorized)
		{
			iv_granted_success.setImageResource(R.drawable.ic_success);
			room_grant.setText("已通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_4bbb4d));
			iv_arrow_right.setVisibility(View.GONE);

			group_room_grant.setEnabled(false);
			room_using_add_time.setEnabled(true);
			room_using_add_time.setBackgroundResource(R.drawable.dialog_sure_btn);
			room_using_add_time.setTextColor(getActivity().getResources().getColor(R.color.white));
			room_using_clear.setEnabled(true);
			room_using_clear.setBackgroundResource(R.drawable.dialog_sure_btn);
			room_using_clear.setTextColor(getActivity().getResources().getColor(R.color.white));
			room_using_to_none.setEnabled(true);
			room_using_to_none.setBackgroundResource(R.drawable.dialog_sure_btn);
			room_using_to_none.setTextColor(getActivity().getResources().getColor(R.color.white));
		} else
		{
			iv_granted_success.setImageResource(R.drawable.ic_warn);
			room_grant.setText("未通过");
			room_grant.setTextColor(getResources().getColor(R.color.color_ffab40));
			iv_arrow_right.setVisibility(View.VISIBLE);
			group_room_grant.setEnabled(true);

			room_using_add_time.setEnabled(false);
			room_using_add_time.setBackgroundResource(R.drawable.dialog_cancel_btn);
			room_using_add_time.setTextColor(getActivity().getResources().getColor(R.color.color_a9a9a9));
			room_using_clear.setEnabled(false);
			room_using_clear.setBackgroundResource(R.drawable.dialog_cancel_btn);
			room_using_clear.setTextColor(getActivity().getResources().getColor(R.color.color_a9a9a9));
			room_using_to_none.setEnabled(false);
			room_using_to_none.setBackgroundResource(R.drawable.dialog_cancel_btn);
			room_using_to_none.setTextColor(getActivity().getResources().getColor(R.color.color_a9a9a9));
		}
	}

	@Override
	public void setValue(String value)
	{
		try
		{
			if (value.contains("."))
				ToastUtils.showText(getActivity(), R.string.error_number);
			else if (Integer.parseInt(value) <= 0)
				ToastUtils.showText(getActivity(), R.string.error_number);
			else
			{
				current_et.setText(value);
			}
		} catch (

		Exception e)
		{
			ToastUtils.showText(getActivity(), getResources().getString(R.string.error_max_number));
		}
	}
}
